package com.sf.tools.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {

	/**
	 * 项目名称
	 */
	public static String MODULE_NAME = "";
	/**表名*/
	public static String TABLE_NAME = "";
	/**表名前缀*/
	public static String[] TABLE_PREFIXS;
	/**实体名称*/
	public static String DOMAIN_NAME = "";
	/**实体描述*/
	public static String DOMAIN_DESC = "";
	/**Dao名称*/
	public static String DAO_NAME = "";
	public static String IDAO_NAME = "";
	/**Biz名称*/
	public static String BIZ_NAME = "";
	public static String IBIZ_NAME = "";
	/**Action名称*/
	public static String ACTION_NAME = "";
	/**实体属性名*/
	public static String PROP_NAME = "";
	/**Dao属性名*/
	public static String PROP_NAME_DAO = "";
	/**Biz属性名*/
	public static String PROP_NAME_BIZ = "";
	/**Action属性名*/
	public static String PROP_NAME_ACTION = "";
	
	public static String PACKAGE_NAME = "";
	
	public static List<String> _COLUMN = new ArrayList<String>();
	public static List<String> _FIELD = new ArrayList<String>();
	public static List<String> _TYPE = new ArrayList<String>();
	public static List<String> _DESC = new ArrayList<String>();
	public static List<String> _LENGTH = new ArrayList<String>();
	
	public static List<String> PRIMATY_KEY = new ArrayList<String>();
	public static List<String> PRIMATY_KEY_COLUMN = new ArrayList<String>();
	
	public static Map<String,String> MAPPING = new HashMap<String,String>();
	public static List<String> IS_QUERY = new ArrayList<String>();
	public static List<String> IS_SHOW = new ArrayList<String>();
	public static List<String> IS_COMBO = new ArrayList<String>();
	
	public static List<String> QUERY = new ArrayList<String>();
	public static List<String> SHOW = new ArrayList<String>();
	public static List<String> COMBO = new ArrayList<String>();
	
	public static String SAVE_PATH;
	
	public static List<String> PROP_NAMES = new ArrayList<String>();
	public static List<String> DOMAIN_DESCS = new ArrayList<String>();
	
	public static String GENERATE_SPRING_TYPE = "";
	public static List<File> files = new ArrayList<File>();
	public static String SEQUENCE_NAME;
	
	public static Map<String,List<String>> primaryKeys = new HashMap<String,List<String>>();
	
	public static List<String> IS_SEARCH = new ArrayList<String>();
	public static List<String> IS_ADD = new ArrayList<String>();
	public static List<String> IS_UPDATE = new ArrayList<String>();
	public static List<String> IS_DELETE = new ArrayList<String>();
	public static List<String> IS_IMPORT = new ArrayList<String>();
	public static List<String> IS_EXPORT = new ArrayList<String>();
	
	public static boolean SEARCH = false;
	public static boolean ADD = false;
	public static boolean UPDATE = false;
	public static boolean DELETE = false;
	public static boolean IMPORT = false;
	public static boolean EXPORT = false;
	
	private static void beforeRender(){
		_COLUMN.clear();
		_FIELD.clear();
		_TYPE.clear();
		_DESC.clear();
		_LENGTH.clear();
		PRIMATY_KEY.clear();
		PRIMATY_KEY_COLUMN.clear();
		
		QUERY.clear();
		SHOW.clear();
		COMBO.clear();
		
		SEARCH = false;
		ADD = false;
		UPDATE = false;
		DELETE = false;
		IMPORT = false;
		EXPORT = false;
	}
	
	public static void init(List<String> isSearch,List<String> isAdd,List<String> isUpdate,
			List<String> isDelete,List<String> isImport,List<String> isExport,
			Map<String, String> mapping, List<String> isQuery, List<String> isShow, List<String> isCombo, 
			String projectName, String generatePath, String[] prefixs){
		IS_SEARCH = isSearch;
		IS_ADD = isAdd;
		IS_UPDATE = isUpdate;
		IS_DELETE = isDelete;
		IS_IMPORT = isImport;
		IS_EXPORT = isExport;
		
		MAPPING = mapping;
		IS_QUERY = isQuery;
		IS_SHOW = isShow;
		IS_COMBO = isCombo;
		
		MODULE_NAME = projectName;
		SAVE_PATH = generatePath+File.separator+MODULE_NAME;
		
		TABLE_PREFIXS = prefixs;
		
		PACKAGE_NAME = "com.sf.module."+MODULE_NAME;
		
		PROP_NAMES = new ArrayList<String>();
		DOMAIN_DESCS = new ArrayList<String>();
	}
	
	
	
	public static void generate(String tableName, String tableDesc, List<String[]> columnInfos){
		TABLE_NAME = tableName;
		DOMAIN_DESC = tableDesc;
		DOMAIN_NAME = getEntityName(TABLE_NAME);
		DAO_NAME = DOMAIN_NAME+"Dao";
		IDAO_NAME = "I"+DOMAIN_NAME+"Dao";
		BIZ_NAME = DOMAIN_NAME+"Biz";
		IBIZ_NAME = "I"+DOMAIN_NAME+"Biz";
		ACTION_NAME = DOMAIN_NAME+"Action";
		
		PROP_NAME = (DOMAIN_NAME.charAt(0)+"").toLowerCase()+DOMAIN_NAME.substring(1);
		PROP_NAME_DAO = PROP_NAME+"Dao";
		PROP_NAME_BIZ = PROP_NAME+"Biz";
		PROP_NAME_ACTION = PROP_NAME+"Action";
		
		PROP_NAMES.add(PROP_NAME);
		DOMAIN_DESCS.add(DOMAIN_DESC);
		
		beforeRender();
		
		for (String[] columnInfo : columnInfos) {
			_COLUMN.add(columnInfo[0]);
			_FIELD.add(getFieldName(columnInfo[0]));
			_TYPE.add(getFieldType(columnInfo[1]));
			String desc = columnInfo[2];
			if(desc!=null){
				desc = desc.replace("（", "(").replace("）", ")").replace("，", ",").trim();
			}
			_DESC.add(desc);
			_LENGTH.add(getLengthDesc(columnInfo[1]));
			
			String primaryKey = columnInfo[3];
			if("Y".equalsIgnoreCase(primaryKey)){
				PRIMATY_KEY.add(getFieldName(columnInfo[0]));
				PRIMATY_KEY_COLUMN.add(columnInfo[0]);
			}
		}
		
		//{HFLS_TS_JOB_STATE:JOB_NAME=true, HFLS_TS_JOB_STATE:JOB_STATE=true}
		for (String str : IS_QUERY) {
			if(TABLE_NAME.equals(str.split(":")[0])){
				QUERY.add(getFieldName(str.split(":")[1]));
			}
		}
		for (String str : IS_SHOW) {
			if(TABLE_NAME.equals(str.split(":")[0])){
				SHOW.add(getFieldName(str.split(":")[1]));
			}
		}
		for (String str : IS_COMBO) {
			if(TABLE_NAME.equals(str.split(":")[0])){
				COMBO.add(getFieldName(str.split(":")[1]));
			}
		}
		
		for(String str : IS_SEARCH){
			if(TABLE_NAME.equals(str)){
				SEARCH = true;
				break;
			}
		}
		for(String str : IS_ADD){
			if(TABLE_NAME.equals(str)){
				ADD = true;
				break;
			}
		}
		for(String str : IS_UPDATE){
			if(TABLE_NAME.equals(str)){
				UPDATE = true;
				break;
			}
		}
		for(String str : IS_DELETE){
			if(TABLE_NAME.equals(str)){
				DELETE = true;
				break;
			}
		}
		for(String str : IS_IMPORT){
			if(TABLE_NAME.equals(str)){
				IMPORT = true;
				break;
			}
		}
		for(String str : IS_EXPORT){
			if(TABLE_NAME.equals(str)){
				EXPORT = true;
				break;
			}
		}
	}
	
	/**
	 * 获取实体类描述
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @param desc
	 * @return
	 */
	public static String getClassDesc(String desc){
		StringBuffer sb = new StringBuffer();
		sb.append("/**").append("\n")
		  .append("* <pre>").append("\n")
		  .append("* *********************************************").append("\n")
		  .append("* Copyright sf-express.").append("\n")
		  .append("* All rights reserved.") .append("\n")
		  .append("* Description: "+desc+"").append("\n")
		  .append("* HISTORY").append("\n")
		  .append("* *********************************************").append("\n")
		  .append("*  ID     DATE          PERSON          REASON").append("\n")
		  .append("*  1      "+getCurrDate()+"    "+getCurrUser()+"          创建") .append("\n")
		  .append("* *********************************************").append("\n")
		  .append("* </pre>").append("\n")
		  .append("*/").append("\n");
		return sb.toString();
	}
	
	/**
	 * 获取方法描述
	 * @return
	 */
	public static String getMethodDesc(String desc, String ...args){
		StringBuffer sb = new StringBuffer();
		sb.append("\t").append("/**").append("\n")
		  .append("\t").append(" * ").append(desc).append("\n")
		  .append("\t").append(" * @author ").append(getCurrUser()).append("\n")
		  .append("\t").append(" * @date ").append(getCurrDate()).append("\n");
		for (String arg : args) {
			sb.append("\t").append(" * @param ").append(arg).append("\n");
		}
		if(args.length > 0){
			sb.append("\t").append(" * @return").append("\n");
		}
		sb.append("\t").append(" */").append("\n");
		return sb.toString();
	}
	
	/**
	 * 当前用户
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @return
	 */
	public static String getCurrUser(){
		String name = "admin";
		try{
			name = System.getProperty("user.name");
		}catch(Exception e){
			e.printStackTrace();
			return name;
		}
		return name;
	}
	
	/**
	 * 当前日期
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @return
	 */
	public static String getCurrDate(){
		String date = "2013-01-01";
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.format(new Date());
		}catch(Exception e){
			e.printStackTrace();
			return date;
		}
		return date;
	}
	
	/**
	 * 根据数据库表名获取实体名称
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @param tableName	TB_GROUP_USER
	 * @return	
	 */
	public static String getEntityName(String tableName){
//		String[] prefixs = {"hfls_tt_","hfls_tm_","hfls_ts_"};
		
		tableName = tableName.toLowerCase();
		for (String prefix : TABLE_PREFIXS) {
			prefix = prefix.toLowerCase();
			if(tableName.startsWith(prefix)){
				tableName = tableName.replace(prefix, "");	//去掉前缀
				break;
			}
		}
//		tableName = tableName.replace("hfls_tt_", "");	//去掉前缀
		while(tableName.startsWith("_")){
			tableName = tableName.substring(1);
		}
		while(tableName.endsWith("_")){
			tableName = tableName.substring(0,tableName.length()-1);
		}
		
		String name = getFieldName(tableName);	//groupUser
		return (name.charAt(0)+"").toUpperCase()+name.substring(1);
	}
	
	/**
	 * 获取字段名称
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @param columnName
	 * @return
	 */
	public static String getFieldName(String columnName){
		while(columnName.endsWith("_")){
			columnName = columnName.substring(0,columnName.length()-1);
		}
		String name = columnName.toLowerCase().trim();
		char[] ch = name.toCharArray();
		for(int i=0;i<ch.length;i++){
			if("_".equals(ch[i]+"")){
				ch[i+1] = ((ch[i+1]+"").toUpperCase()).charAt(0);
			}
		}
		String s = new String(ch).replace("_", "");
		return s;
	}
	
	public static String getColumnName(String fieldName){
		String regex = "[A-Z]";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(fieldName);
		while(m.find()){
			String s = m.group();
			fieldName = fieldName.replace(s, "_"+s.toLowerCase());
		}
		return fieldName.toUpperCase();
	}
	
	/**
	 * 获取字段类型
	 * @author sfhq217
	 * @date 2013-12-30 
	 * @param columnType
	 * @return
	 */
	public static String getFieldType(String columnType){
		String type = columnType.toLowerCase().trim();
		if(type.matches("number[(]\\d{2}[)]")){
			return "Long";
		}else if(type.matches("number[(]\\d{1}[)]")){
			return "Integer";
		}else if(type.matches("number[(]\\d+\\,\\d+[)]")){
			return "Double";
		}else if(type.matches("date")){
			return "Date";
		}else if(type.indexOf("char") != -1 || type.indexOf("varchar2") != -1 || type.indexOf("nvarchar2") != -1){
			return "String";
		}else if(type.matches("number")){
			return "Long";
		}else if(type.startsWith("char")){		//MySql
			return "String";
		}else if(type.startsWith("int")){		//MySql
			return "Integer";
		}else if(type.startsWith("double")){	//MySql
			return "Double";
		}
		return "String";
	}
	
	public static String getLengthDesc(String columnType){
		Pattern p = Pattern.compile("number[(](\\d{1,2})[)]",Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(columnType);
		if(m.find()){
			return "precision=\""+m.group(1)+"\"";
		}
		
		p = Pattern.compile("number[(](\\d+)\\,(\\d+)[)]",Pattern.CASE_INSENSITIVE);
		m = p.matcher(columnType);
		if(m.find()){
			return "precision=\""+m.group(1)+"\" scale=\""+m.group(2)+"\"";
		}
		
		p = Pattern.compile("varchar2[(](\\d+)[)]",Pattern.CASE_INSENSITIVE);
		m = p.matcher(columnType);
		if(m.find()){
			return "length=\""+m.group(1)+"\"";
		}
		
		p = Pattern.compile("char[(](\\d+)[)]",Pattern.CASE_INSENSITIVE);
		m = p.matcher(columnType);
		if(m.find()){
			return "length=\""+m.group(1)+"\"";
		}
		
		p = Pattern.compile("date",Pattern.CASE_INSENSITIVE);
		m = p.matcher(columnType);
		if(m.find()){
			return "length=\"7\"";
		}
		
		return "";
	}
	
	/**
	 * 获取查询字段描述
	 * @author sfhq217
	 * @date 2014-1-3 
	 * @param query
	 * @return
	 */
	public static String getQueryDesc(String query){
		int k = -1;
		for(int i=0;i<_FIELD.size();i++){
			if(_FIELD.get(i).equals(query)){
				k = i;
				break;
			}
		}
		if(-1 == k){
			return "";
		}
		return _DESC.get(k)==null?"":_DESC.get(k);
	}
	
	/**
	 * 获取查询字段类型
	 * @author sfhq217
	 * @date 2014-1-3 
	 * @param query
	 * @return
	 */
	public static String getQueryType(String query){
		int k = -1;
		for(int i=0;i<_FIELD.size();i++){
			if(_FIELD.get(i).equals(query)){
				k = i;
				break;
			}
		}
		if(-1 == k){
			return "";
		}
		return _TYPE.get(k);
	}
	
	public static void write(File file,String content){
//		PrintWriter pw = null;
//		try {
//			pw = new PrintWriter(file);
//			pw.write(content);
//			pw.close();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
		
		try {
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
			out.write(content);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean endWithSuffixs(String fileName,List<String> suffixs){
		for (String suffix : suffixs) {
//			System.out.println(fileName + "---" + suffix);
			if(fileName.endsWith(suffix)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取指定目录下以指定的后缀名结束的所有文件
	 * @author 徐益森(sfhq217)
	 * @date 2012-10-16 
	 * @param path 文件夹路径
	 * @param name 后缀名,name如果为 null 或 "" 则获取所有文件
	 * @param isdepth 是否包含子目录
	 * @return
	 */
	public static List<File> findFilesByFileName(String path, final List<String> suffixs, final boolean isdepth){
		File file = new File(path);
		if(file.exists()){
			if(file.isDirectory()){
				File[] listFiles = file.listFiles(new FileFilter(){
					@Override
					public boolean accept(File f) {
						if(f.isDirectory() && isdepth==true){
							return true;
						}
//						if(f.isFile() && (name==null || "".equals(name.trim()))){
//							return true;
//						}
						if(f.isFile()){
							return true;
						}
						return false;
					}
				});
				for (File file2 : listFiles) {
					//过滤 .svn 文件
					if(file.getName().toLowerCase().endsWith(".svn")) continue;
					
					if(file2.isFile() && endWithSuffixs(file2.getName(),suffixs)){
//						System.out.println(file2.getPath());
						files.add(file2);
					}else{
						findFilesByFileName(file2.getPath(),suffixs,isdepth);
					}
				}
			}
		}
		return files;
	}
	
	public static void main(String[] args) {
		System.out.println(getFieldName("User_Group"));
		Map<String,Boolean> maps = new HashMap<String,Boolean>();
		maps.put("tb_user:name", true);
		maps.put("tb_user:age", true);
		maps.put("tb_user:sex", true);
		
	}
}
